package com.md.youyouhui.ui.user;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityUserInfoBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.UserInfoResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.login.LoginActivity;
import com.md.youyouhui.utils.AppManager;
import com.md.youyouhui.utils.GlideApp;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by AdministratorZJ
 * on 2019/4/9.
 *
 * @author AdministratorZJ
 */
public class UserInfoActivity extends BaseActivity {
    private ActivityUserInfoBinding infoBinding;
    private Bitmap head;
    private Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "head.jpg");
    private MainViewModel viewModel;
    private String mobile;

    @Override
    public void setContentLayout() {
        infoBinding = DataBindingUtil.setContentView(this, R.layout.activity_user_info);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        setSupportActionBar(infoBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void initData() {
        infoBinding.infoHeadIcon.setOnClickListener(v -> showCameraDialog());
        infoBinding.infoNick.setOnClickListener(v -> upDateName());
        infoBinding.infoSafe.setOnClickListener(v -> startActivity(new Intent(UserInfoActivity.this, UserSafeActivity.class).putExtra("phone", mobile)));
        infoBinding.userExit.setOnClickListener(v -> {
            new AlertDialog.Builder(ct).setMessage("退出登录").setPositiveButton("确定", (dialog, which) -> {
                SharedPreferencesUtils.saveString(UserInfoActivity.this, Constants.USER_TOKEN, "");
                AppManager.getAppManager().finishAllActivity();
                startActivity(new Intent(ct, LoginActivity.class));
                finish();
            }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).show();
        });
        getUserInfo();
    }

    private void getUserInfo() {
        viewModel.getUserInfo().observe(this, userInfoResponse -> {
            assert userInfoResponse != null;
            switch (userInfoResponse.status) {
                case LOADING:
                    infoBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    infoBinding.progress.setVisibility(View.GONE);
                    UserInfoResponse data = userInfoResponse.data;
                    if (null == data) {
                        return;
                    }
                    GlideApp.with(this).load(data.head).centerCrop().into(infoBinding.camera);
                    infoBinding.nickName.setText(data.nickname);
                    mobile = data.mobile;
                    break;
                case ERROR:
                    infoBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, userInfoResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void showCameraDialog() {
        new AlertDialog.Builder(this)
                .setMessage("请选择上传方式")
                .setNegativeButton("照相机", (dialog, which) -> isOpenCamera())
                .setPositiveButton("相册", (dialog, which) -> {
                    // 从相册里面取照片
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 1);
                }).show();
    }

    private void isOpenCamera() {
        //换头像请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //说明没有开权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
            } else {
                // 调用相机拍照
                startCamera();
            }
        } else {
            // 调用相机拍照
            startCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 100: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 调用相机  Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg"))
                    startCamera();
                } else {
                    Toast.makeText(ct, "摄像头权限没有打开", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            default:
                break;
        }
    }

    private void upDateName() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.dialog_soft_input).setTitle("请输入昵称");
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null);
        EditText name = view.findViewById(R.id.etName);
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.setPositiveButton("确定", null);
        AlertDialog dialog = builder.setView(view, 0, 20, 0, 0).show();
        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
            if (TextUtils.isEmpty(name.getText())) {
                Toast.makeText(ct, "请输入昵称", Toast.LENGTH_SHORT).show();
                return;
            }
            modileName(name.getText().toString());
            dialog.dismiss();
        });
    }

    private void modileName(String name) {
        viewModel.mobileName(name).observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case LOADING:
                    infoBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    infoBinding.progress.setVisibility(View.GONE);
                    Toast.makeText(ct, "修改成功", Toast.LENGTH_SHORT).show();
                    infoBinding.nickName.setText(name);
                    break;
                case ERROR:
                    infoBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(UserInfoActivity.this, objectResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void startCamera() {
        File file = new File(this.getFilesDir(), "head.jpg");
        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent2.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".FileProvider", file));
        } else {
            intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
        }
        // 采用ForResult打开
        startActivityForResult(intent2, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    // 裁剪图片
                    cropPhoto(data.getData());
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File filesDir = this.getFilesDir();
                    //data/user/0/com.kl.fuling/files
                    //"/storage/emulated/0/temp/1474960080319.jpg"
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        File temp = new File(this.getFilesDir() + "/head.jpg");
                        cropPhoto(FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".FileProvider", temp));
                    } else {
                        File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                        // 裁剪图片
                        cropPhoto(Uri.fromFile(temp));
                    }
                }
                break;
            case 3:
                if (data != null) {
                    try {
                        head = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uritempFile));
                        if (head != null) {
                            /**
                             * 上传服务器代码
                             */
                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            head.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                            addChildService(outputStream.toByteArray());
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "找不到图片文件", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void addChildService(byte[] head) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), head);
        builder.addFormDataPart("file", System.currentTimeMillis() + ".png", requestBody);
        viewModel.setUserHead(builder.build()).observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case LOADING:
                    infoBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    infoBinding.progress.setVisibility(View.GONE);
                    Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                    GlideApp.with(this).load(head).transforms(new RoundedCornersTransformation(30, 0)).into(infoBinding.camera);
                    break;
                case ERROR:
                    infoBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, objectResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //这段代码判断，在安卓7.0以前版本是不需要的。特此注意。不然这里也会抛出异常
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.putExtra("noFaceDetection", false);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);

    }
}
